package admin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"jwgin/model/mysql"
	"jwgin/service"
	"jwgin/utils/salt"
	"jwgin/utils/sign"
	"time"
	"unicode/utf8"
)

type company struct {
}

func (l *company) Routers(Router *gin.RouterGroup) (R gin.IRoutes) {
	Router.GET("company", l.get)
	Router.PUT("company", l.put)
	Router.POST("company", l.post)
	return Router
}

//获取所有公司
func (company) get(c *gin.Context) {
	count, size, offset := pages(c)

	db := service.G.Model(mysql.Company{})

	//公司名称
	if title := c.Query("title"); title != "" {
		db = db.Where("title = ?", title)
	}

	//账号
	if account := c.Query("account"); account != "" {
		db = db.Where("account = ?", account)
	}

	//时间筛选
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	if startTime != "" && endTime != "" {
		db = db.Where(" `addtime` > ? AND `addtime` < ? ", startTime, endTime)
	}

	list := []map[string]interface{}{}
	db.Select(`id`, `title`, `account`, `state`, `addtime`, `uptime`, `bean`).Count(&count).Offset(offset).Limit(size).Order("id DESC").Scan(&list)
	RespList(c, count, list)
}

//添加
func (company) put(c *gin.Context) {
	requ := &mysql.Company{}
	if err := c.ShouldBind(requ); err != nil {
		RespErr(c, err)
		return
	}

	if utf8.RuneCountInString(requ.Title) > 64 || utf8.RuneCountInString(requ.Title) < 6 {
		RespErr(c, fmt.Errorf("公司名 6-64 位"))
		return
	}

	if len(requ.Account) > 16 || len(requ.Account) < 6 {
		RespErr(c, fmt.Errorf("账号 6-16 位"))
		return
	}

	if len(requ.Password) > 16 || len(requ.Password) < 6 {
		RespErr(c, fmt.Errorf("密码6-16位"))
		return
	}

	if requ.State < 1 {
		requ.State = 2
	}

	com := &mysql.Company{}
	if err := service.G.Model(mysql.Company{}).Where("title = ? Or account = ? ", requ.Title, requ.Account).First(com).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			RespErr(c, err)
			return
		}
	}

	if com.Title == requ.Title {
		RespErr(c, fmt.Errorf("该公司已注册"))
		return
	}

	if com.Account == requ.Account {
		RespErr(c, fmt.Errorf("该账号已注册"))
		return
	}

	requ.Salt = salt.SaltStr(6)
	requ.Password = sign.HmacSha256(requ.Salt, requ.Password)
	requ.Addtime = time.Now().Unix()
	requ.Uptime = time.Now().Unix()
	service.G.Create(requ)
	RespSucc(c, nil)

}

//更新
func (company) post(c *gin.Context) {
	requ := &mysql.Company{}
	if err := c.ShouldBind(requ); err != nil {
		RespErr(c, err)
		return
	}

	com := &mysql.Company{}
	if err := service.G.Model(mysql.Company{}).Where("id = ? ", requ.Id).First(&com).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			RespErr(c, err)
			return
		} else {
			RespErr(c, fmt.Errorf("找不到要修改的公司"))
			return
		}
	}

	if requ.Password != "" {
		password := sign.HmacSha256(com.Salt, requ.Password)
		service.G.Model(&mysql.Company{}).Where("id = ? ", requ.Id).Updates(map[string]interface{}{
			"state":    requ.State,
			"password": password,
		})
	} else {
		service.G.Model(&mysql.Company{}).Where("id = ? ", requ.Id).Update("state", requ.State)
	}
	RespSucc(c, nil)
}
